package com.yunqing.restkeeper.shop.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.yunqing.restkeeper.common.tenant.TenantContext;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.stereotype.Component;

/**
 * @ClassName CustomTenantHandler
 * @Description TODO
 * @author: puyunqing
 * @Date: 2025/6/30
 */
@Component
@Slf4j
public class CustomTenantHandler implements TenantLineHandler {

    //定义当前的多租户标识字段
    private static final String SYSTEM_TENANT_ID = "shop_id";

    @Override
    public Expression getTenantId() {
        //暂时写死，用于测试
        //String shopId="test";
        //从RPCContext对象中获取shopid
        log.info("CustomTenantHandler-----------shopId-----------" + RpcContext.getServerAttachment().getAttachment("shopId"));
//        String shopId = RpcContext.getServerAttachment().getAttachment("shopId");
        String shopId = RpcContext.getServerAttachment().getAttachment("shopId");

        if (shopId == null){
            throw new RuntimeException("get tenantId error");
        }
        return new StringValue(shopId);
    }

    @Override
    public String getTenantIdColumn() {
        return SYSTEM_TENANT_ID;
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 根据需要返回是否忽略该表
        return false;
    }

    // 假设您有一个 TenantContext 类来存储和获取租户ID
    static class TenantContextHolder {
        private static final ThreadLocal<Long> currentTenantId = new ThreadLocal<>();

        public static void setCurrentTenantId(Long tenantId) {
            currentTenantId.set(tenantId);
        }

        public static String getCurrentTenantId() {
           return null;
        }

        public static void clear() {
            currentTenantId.remove();
        }
    }
}


